package com.appkubes.fintech.admin.application.risk.data.boole.utils.interceptor;

import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * 重试拦截器
 */
@Slf4j
public class RetryIntercepter implements Interceptor {

    public int maxRetry;//最大重试次数
    private int retryNum = 0;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
    //重试机制 时间间隔
    private ImmutableList<Integer> intervalList = ImmutableList
            .of(30000, 60000, 180000,300000);

    public RetryIntercepter(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url();
        Response response = chain.proceed(request);
        while (!response.isSuccessful() && retryNum < maxRetry) {
            try {
                Thread.sleep(intervalList.get(retryNum));
                System.out.println("请求url:" + url + ",重试次数:" + retryNum
                        +",请求延迟:"+intervalList.get(retryNum)+"ms");
                retryNum++;
                response = chain.proceed(request);
            } catch (Exception e) {
                log.error("http重试请求异常：{}",e);
            }
        }
        return response;
    }
}